package com.habo.controller;

import com.alibaba.fastjson.JSON;
import com.habo.entity.WeiBo;
import com.habo.service.PagerUtilService;
import com.habo.service.WeiBoService;
import com.habo.util.PagerUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 微博控制器
 * Created by jiuyou on 2017/3/27 0027.
 */
@Controller
public class WeiBoController {
    @Resource
    private WeiBoService weiBoService;
    @Resource
    private PagerUtilService pagerUtilService;

    @RequestMapping(value = "index")
    public String index() {
        return "index";
    }

    @RequestMapping(value = "my")
    public String myjsp() {
        return "myjsp";
    }

    @RequestMapping(value = "testphoto")
    public String testphoto() {
        return "testphoto";
    }

    @RequestMapping(value = "test2")
    public String test2() {
        return "test2";
    }


    /**
     * 发布微博
     */
    @RequestMapping(value = "addWeiBo")
    public String addWeiBo(WeiBo weiBo, HttpServletRequest request, @RequestParam("files") MultipartFile[] files) throws IOException {
        //获得物理路径webapp所在路径
        //  String pathRoot = request.getSession().getServletContext().getRealPath("");

        String wbpicture = "";
        List<String> listImagePath = new ArrayList<String>();
        for (MultipartFile mf : files) {
            if (!mf.isEmpty()) {
                //生成uuid作为文件名称

                //  String uuid = UUID.randomUUID().toString().replaceAll("-","");
                //获得文件类型（可以判断如果不是图片，禁止上传）
                String contentType = mf.getContentType();
                //获得文件后缀名称
                String imageName = contentType.substring(contentType.indexOf("/") + 1);
                String filepath = request.getSession().getServletContext()
                        .getRealPath("/")
                        + "/fileupload/" + mf.getOriginalFilename();
                mf.transferTo(new File(filepath));
                wbpicture = wbpicture + mf.getOriginalFilename() + ",";

            }
        }
        weiBo.setWbpicture(wbpicture);
        weiBoService.addWeiBo(weiBo);
        return "index";
    }

    /**
     * 查询全部微博
     *
     * @return
     */
    @RequestMapping(value = "ssss")
    public String ssss() {
        return "index";
    }

    @RequestMapping(value = "findAllWeiBo")
    @ResponseBody
    public void findAllWeiBo(Model model, HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("utf-8");


        String pageNumStr = request.getParameter("pageNum");
        String pageSizeStr = request.getParameter("pageSize");
        int pageSize = Integer.parseInt(pageSizeStr);
        int pageNum = Integer.parseInt(pageNumStr);

        PagerUtil<WeiBo> result = pagerUtilService.findAllWeiBo(pageNum, pageSize);

        for (WeiBo weiBo : result.getDataList()) {
            //匹配表情
            String wbcontentString = weiBo.getWbcontent();
            Pattern pattern = Pattern.compile("\\[([\\u4E00-\\u9FA5]{1,2})\\]");//匹配[]
            Matcher matcher = pattern.matcher(wbcontentString);
            while (matcher.find()) {
                String imgNo = matcher.group(1);//匹配[]里面的表情名称
                wbcontentString = wbcontentString.replace("[" + imgNo + "]", "<img src='gif/" + imgNo + ".gif'/>");
            }
            weiBo.setWbcontent(wbcontentString);
        }

        //匹配图片
        for (WeiBo weiBo : result.getDataList()) {
            String wbpic = weiBo.getWbpicture();
            Pattern p = Pattern.compile("(\\w+).(jpg|gif|png|bmp|jpeg)");//解析正则表达式
            Matcher matcher = p.matcher(wbpic);
            while (matcher.find()) {//有匹配的子串就进入循环
                String imgNo = matcher.group(0);//获得匹配的子串（）里的字符串
                wbpic = wbpic.replace(imgNo + ",", "<img class='showpic' src='fileupload/" + imgNo + "'>");//替换成标签和地址
            }
            weiBo.setWbpicture(wbpic);
        }

        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("text/html;charset=utf-8");

        String responseStr = JSON.toJSONString(result);
        Writer writer = response.getWriter();
        writer.write(responseStr);
        writer.flush();

        //  model.addAttribute("weiBoList",weiBoList);
        // return "index";
    }

    //  List<WeiBo> weiBoList=weiBoService.findAllWeiBo();


       /* for (WeiBo weiBo:weiBoList){
            //匹配表情
            String wbcontentString=weiBo.getWbcontent();
            Pattern pattern=Pattern.compile("\\[([\\u4E00-\\u9FA5]{1,2})\\]");//匹配[]
            Matcher matcher=pattern.matcher(wbcontentString);
            while (matcher.find()){
                String imgNo=matcher.group(1);//匹配[]里面的表情名称
                wbcontentString=wbcontentString.replace("["+imgNo+"]","<img src='gif/"+imgNo+".gif'/>");
            }
           weiBo.setWbcontent(wbcontentString);
        }

        //匹配图片
        for(WeiBo weiBo:weiBoList){
            String wbpic=weiBo.getWbpicture();
            Pattern p=Pattern.compile("(\\w+).(jpg|gif|png|bmp|jpeg)");//解析正则表达式
            java.util.regex.Matcher matcher = p.matcher(wbpic);
            while (matcher.find()) {//有匹配的子串就进入循环
                String imgNo = matcher.group(0);//获得匹配的子串（）里的字符串
                wbpic=wbpic.replace(imgNo+",","<img class='showpic' src='fileupload/" + imgNo+"'>");//替换成标签和地址
            }
            weiBo.setWbpicture(wbpic);
        }*/
}
